<?php
/**
 * Created by PhpStorm.
 * User: ljc
 * Date: 2018/6/18
 * Time: 15:13
 */

namespace houdun\model;
use PDO;
use Exception;

class Base{
	private static $pdo;
	private $table;
	private $where='';
	private $order='';
	private $field='*';
	private $pri;
	public function __construct ($table) {
		//为什么要有这个判断
		if(is_null (self::$pdo)){
			try{
				$dsn = 'mysql:host='.c('database.dbhost').';dbname='.c('database.dbname');
				$username = c('database.username');
				$password = c('database.password');
				self::$pdo = new PDO($dsn,$username,$password);
				//设置字符集
				self::$pdo->query ('set names utf8');
				//设置错误属性
				self::$pdo->setAttribute (PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
			}catch (Exception $e){
				die($e->getMessage ());
			}
		}

		$this->table=strtolower (ltrim(strrchr($table,'\\'),'\\'));

	}
	public function getAll(){

		$sql='select '.$this->field.' from '.$this->table.$this->where.$this->order;
		return $this->q($sql);
	}
	public function field($field){
		$this->field=$field;

		return $this;
	}
	public function del(){
		$sql='delete from '.$this->table.$this->where;
		$this->e($sql);
	}
	public function update($data){
		if(is_null($this->where)) return false;
		$fields='';
		foreach($data as $k=>$v){
			$v=is_int ($v)?$v:"'$v'";
			$fields.=$k.'='.$v.',';
		}
		$fields=rtrim($fields,',');
		$sql='update '.$this->table.' set '.$fields.$this->where;
		$this->e($sql);

	}
	public function insert($data){
		$fields='';
		$values='';
		foreach($data as $k=>$v){
			$fields.=$k.',';
			$values.=is_int ($v)?$v.',':"'$v'".',';
		}
		$fields=rtrim($fields,',');
		$values=rtrim($values,',');
		$sql='insert into '.$this->table.' ('.$fields.') values('.$values.')';
		$this->e($sql);
	}
	public function order($str){
		$sql=' order by '.$str;
		$this->order=$sql;
		return $this;
	}
	public function where($str){
		$sql=' where '.$str;
		$this->where=$sql;
		return $this;
	}
	public function find($primary){
		$pk=$this->getPk();
		$sql='select * from '.$this->table.' where '.$pk.'='.$primary;
		return current($this->q($sql));
	}
	private function getPk(){
		$sql='desc '.$this->table;
		$res=$this->q($sql);
		foreach($res as $field){
			if($field['Key']=='PRI'){
				return $this->pri=$field['Field'];
			}
		}
	}
	/**
	 * 执行有结果集的操作：select
	 * @param $sql
	 *
	 * @return array
	 */
	public function q($sql){
		//调用pdo query
		try{

			return self::$pdo->query ($sql)->fetchAll (PDO::FETCH_ASSOC);
		}catch (Exception $e){
			die($e->getMessage ());
		}
	}

	/**
	 * @param $sql	sql语句
	 *
	 * @return int	返回受影响的行数
	 */
	public function e($sql){
		//异常捕获
		try{
			//返回sql语句执行后的结果
			return $res=self::$pdo->exec ($sql);
		}catch(Exception $e){
			die($e->getMessage ());
		}
	}
}